<?php
namespace app\admin\middleware;

use app\admin\exception\AuthException;
use app\admin\module\LoginModule;
use app\admin\util\Aes;

class Auth{

    public function handle($request, \Closure $next){
        $token = $request->header("token");
        if(empty($token)){
            $token = $request->param("token"); //兼容wangEditor
        }
        $action = $request->action();
        $controller = $request->controller();
        if($controller == 'Login' && $action == 'login'){
            return $next($request);
        }
        $aes = new Aes();
        $res = $aes->getToken($token);
        if(empty($res)){
            throw new AuthException("登录超时");
        }
        //判断登录是否过期
        $request->uid = $res['uid'];
        if($res["expires_in"] + $res['login_time'] < time()){
            throw new AuthException("登录超时");
        }
        //判断权限
        $permission = LoginModule::permission($res['uid']);
        if(!in_array(strtolower($controller.":".$action),$permission)){
            $userinfo = LoginModule::info($res['uid']);
            $whiteList = [
                "login:info",
                "login:logout"
            ];
            if(!$userinfo['is_super'] && !in_array(strtolower($controller.":".$action),$whiteList)){
                throw new AuthException("没有该权限");
            }
        }
        //权限分为目录权限 后台的目录 以及操作 目录是在后台返回的 操作权限是在这里判断  操作权限属于某个目录

        return $next($request);
    }

}